package com.HQCourse.vod.vod.service.impl;

import com.HQCourse.vod.vod.service.VideoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.HQCourse.model.vod.Chapter;
import com.HQCourse.vod.vod.mapper.ChapterMapper;
import com.HQCourse.vod.vod.service.ChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.HQCourse.model.vod.Video;
import com.example.HQCourse.vo.vod.ChapterVo;
import com.example.HQCourse.vo.vod.VideoVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author zww
 * @since 2023-06-25
 */
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {
    @Autowired
    private VideoService videoService;
    //大纲列表
    @Override
    public List<ChapterVo> getTreeList(Long couresed) {
        List<ChapterVo> chapterVos=new ArrayList<>();

        QueryWrapper<Chapter> chapterQueryWrapper=new QueryWrapper<>();
        //更据课程id获取课程里所有章节
        chapterQueryWrapper.eq("course_id",couresed);
        List<Chapter> chapters = baseMapper.selectList(chapterQueryWrapper);
        //根据id获取课程里面所有小节
        LambdaQueryWrapper<Video> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Video::getCourseId,couresed);
        List<Video> list = videoService.list(lambdaQueryWrapper);
        for (int a=0;a<chapters.size();a++){
            //得到课程每个章节
            Chapter chapter = chapters.get(a);
            ChapterVo chapterVo=new ChapterVo();
            BeanUtils.copyProperties(chapter,chapterVo);
            //得到每个章节放到list集合中去
            chapterVos.add(chapterVo);
            //封装小节部分
            List<VideoVo> listVideo=new ArrayList<>();
            for (Video video:list) {
                //判断小节在那个章节里面  小节id和章节id是否相等
                if(chapter.getId().equals(video.getChapterId())){
                    VideoVo videoVo=new VideoVo();
                    BeanUtils.copyProperties(video,videoVo);
                    listVideo.add(videoVo);
                }
            }
            //把章节里面所有小节放到相对应的章节里面
            chapterVo.setChildren(listVideo);
        }


        return chapterVos;
    }

    @Override
    public void removeChapterByCourseId(Long id) {
        QueryWrapper<Chapter> wrapper=new QueryWrapper<>();
        wrapper.eq("course_id",id);
        baseMapper.delete(wrapper);

    }
}
